# -*- coding: utf-8 -*-
# created by Src - 一路好时光


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

# 发件人和收件人的邮箱地址
sender_email = 'srchao007@163.com'
receiver_email = 'srchao007@163.com'
password = 'GJAANJNROECTMCEK'

# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = '学python发送的第三封邮件-html+图片'

# 设置邮件头信息
mail_body = '''
 <h5>hello,⼩哥哥</h5>
 <p>
    src
 <p><img src="cid:image1"></p>
 </p>
'''

# 允许添加图⽚
msgAlternative = MIMEMultipart('alternative')
msgAlternative.attach(MIMEText(mail_body, 'html', 'utf-8'))
msg.attach(msgAlternative) # 把邮件正⽂内容添加到msg_root⾥

# # 添加附件（如果有的话）
filename = '卡通.jpeg'  # 假设附件是当前目录下的example.txt文件
fp = open(filename, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)


# 连接到SMTP服务器并发送邮件
server = None
try:
    server = smtplib.SMTP_SSL('smtp.163.com', 465)  # 使用SSL连接
    server.login(sender_email, password)
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)
    print("邮件发送成功")
except Exception as e:
    print(f"邮件发送失败：{e}")
finally:
    server.quit()
